<template>
  <!-- 项目工序关系表表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    :width="!props.isReadonly ? '400px' : '400px'"
    draggable
    @close="closeDialog"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="80"
      v-show="!props.isReadonly"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="项目" prop="projectId" style="width: 100%">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.projectId"
              placeholder="请输入项目"
              clearable
              @change="projectIdChange"
              style="width: 100%"
            >
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="`${item.projectCode}`"
                :value="item.id"
              />
            </el-select>

            <span v-else>{{ formData.projectName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="工序" prop="processId" style="width: 100%">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.processId"
              :disabled="!formData.projectId"
              placeholder="请输入工序"
              clearable
              @change="processIdChange"
              style="width: 100%"
            >
              <el-option
                v-for="item in processList"
                :key="item.id"
                :label="`${item.processCode}`"
                :value="item.id"
              />
            </el-select>
            <span v-else>{{ formData.processName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remarks" style="width: 100%">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.remarks"
              placeholder="请输入备注"
              clearable
            />

            <span v-else>{{ formData.remarks }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="是否启用" prop="enabled">
            <el-radio-group v-model="formData.enabled" v-if="!props.isReadonly">
              <el-radio label="1">启用</el-radio>
              <el-radio label="0">停用</el-radio>
            </el-radio-group>

            <span v-else>{{ formData.enabled === "1" ? "启用" : "停用" }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-descriptions
      v-show="props.isReadonly"
      class="margin-top"
      title=""
      :column="1"
      size="large"
      border
    >
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">项目</div>
        </template>

        <div style="width: 100%; word-break: break-all">
          {{ formData.projectCode || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">工序</div>
        </template>

        <div style="width: 100%; word-break: break-all">
          {{ formData.processCode || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item :span="2">
        <template #label>
          <div class="cell-item">是否启用</div>
        </template>
        <el-tag v-show="formData.enabled === '1'" type="">启用</el-tag>
        <el-tag v-show="formData.enabled !== '1'" type="info">停用</el-tag>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">备注</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.remarks || "暂无备注" }}
        </div>
      </el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MDMMDMPROJECTPROCESSADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  processId: [],
  projectId: [],
  enabled: [],
  remarks: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  processId: "",
  processName: "",
  processCode: "",
  projectId: "",
  projectName: "",
  projectCode: "",
  enabled: "1",
  remarks: "",
  deleted: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        processId,
        processName,
        processCode,
        projectId,
        projectName,
        projectCode,
        enabled,
        remarks,
        deleted,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        processId,
        processName,
        processCode,
        projectId,
        projectName,
        projectCode,
        enabled,
        remarks,
        deleted,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.processId = "";
  formData.processName = "";
  formData.processCode = "";
  formData.projectId = "";
  formData.projectName = "";
  formData.projectCode = "";
  formData.enabled = "1";
  formData.remarks = "";
  formData.deleted = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
}

const loading = ref(false);

/** 项目工序关系表保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mdm/mdmprojectprocess/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 获取项目
const projectList = ref([]);
const getProjectList = async () => {
  const res = await request({
    url: "/mdm/mdmprojectinfo/getList",
    method: "post",
    data: {},
  });
  projectList.value = res.data;
  console.log("projectList.value", projectList.value);
};

const projectIdChange = (e) => {
  if (e) {
    projectList.value.forEach((item) => {
      if (item.id == e) {
        formData.projectName = item.projectName;
        formData.projectCode = item.projectCode;
      }
    });
  } else {
    formData.projectName = "";
    formData.projectCode = "";
  }
};

// 获取工序
const processList = ref([]);
const getProcessList = async () => {
  const res = await request({
    url: `/mdm/mdmprocess/getList`,
    method: "post",
    data: {},
  });
  processList.value = res.data;
  console.log("processList.value", processList.value);
};
const processIdChange = (e) => {
  if (e) {
    processList.value.forEach((item) => {
      if (item.id == e) {
        formData.processName = item.processName;
        formData.processCode = item.processCode;
      }
    });
  } else {
    formData.processName = "";
    formData.processCode = "";
  }
};
onMounted(() => {
  getProjectList();
  getProcessList();
});

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
<style lang="scss" scoped>
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 100px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
}
</style>
